package org.workdemo.back.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.workdemo.back.Enum.OperationType;
import org.workdemo.back.anno.AutoFill;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDate;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* org.workdemo.back.mapper.*.*(..))  && @annotation(org.workdemo.back.anno.AutoFill)" )
    void pointCut() {}

    /**
     * 前置通知，实现自动公共日期填充
     */

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("开始自动填充");
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill anno = method.getAnnotation(AutoFill.class);
        if(anno == null) {return;}

        //获取传入方法的参数=》DzyhThb
        Object param = joinPoint.getArgs()[0];

        //如果操作类型是插入
        if (anno.value() == OperationType.INSERT){
            Method setJdrq = param.getClass().getDeclaredMethod("setJdrq", LocalDate.class);
            setJdrq.setAccessible(true);

            setJdrq.invoke(param,LocalDate.now());
            log.info(param.toString());
        }

    }
}
